package org.example;

import java.util.*;

public class BinaryTree {
    static class TreeNode {
        public char val;
        private TreeNode left;
        private TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }
    //前序遍历
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }
    //中序遍历
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }
    //后序遍历
    public void postOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }

    public static int nodeSize = 0;

    /**
     * 获取树中的节点个数 递归思路
     */
    public void size(TreeNode root) {
        if (root == null) return;
        nodeSize++;
        size(root.left);
        size(root.right);
    }

    /**
     * 获取树中的节点个数 子问题思路
     */
    public int size2(TreeNode root) {
        if (root == null) return 0;
        return size2(root.left) + size2(root.right) + 1;
    }

    /**
     * 获取叶子节点的个数 递归思路
     */
    public static int leafSize = 0;

    public void getLeafSize(TreeNode root) {
        if (root == null) return;
        if (root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafSize(root.left);
        getLeafSize(root.right);
    }
    /**
     * 获取叶子节点的个数 递归思路
     */
    public int getLeafSize2(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafSize2(root.left) + getLeafSize2(root.right);
    }

    /**
     * 获取第k层节点的个数
     */
    public int getKLevelSize(TreeNode root, int k) {
        if (root == null) return 0;
        if (k == 1) {
            return 1;
        }
        return getKLevelSize(root.left, k-1) + getKLevelSize(root.right, k-1);
    }
    /**
     * 获取二叉树的高度
     */
    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return Math.max(leftHeight, rightHeight) + 1;
    }

    /**
     * 检测为value的值是否存在
     */
    public TreeNode find(TreeNode root, char value) {
        if (root == null) return null;
        if (root.val == value) {
            return root;
        }
        TreeNode leftVal = find(root.left, value);
        TreeNode rightVal = find(root.right, value);
        if (leftVal != null) {
            return leftVal;
        }
        if (rightVal != null) {
            return rightVal;
        }
        return null;

    }
    /**
     * 层序遍历
     */
    public void levelOrder(TreeNode root) {
        if (root == null) return;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode top = queue.poll();
            System.out.print(top.val + " ");
            if (top.left != null) {
                queue.offer(top.left);
            }
            if (top.right != null) {
                queue.offer(top.right);
            }
        }
    }

    /**
     * 有返回值的层序遍历
     * @param root
     * @return
     */
    public List<List<TreeNode>> levelOrder2(TreeNode root) {
        if (root == null) return new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<List<TreeNode>> res = new ArrayList<>();
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<TreeNode> list = new ArrayList<>();
            while (size-- > 0) {
                TreeNode top = queue.poll();
                list.add(top);
                if (top.left != null) {
                    queue.offer(top.left);
                }
                if (top.right != null) {
                    queue.offer(top.right);
                }
            }
            res.add(list);
        }
        return res;
    }

    /**
     * 自定向上的层序遍历
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while (size-- > 0) {
                TreeNode top = queue.poll();
                //list.add(top.val);     放在力扣上可跑，放在这里会报错 类型不匹配
                if (top.left != null) {
                    queue.offer(top.left);
                }
                if (top.right != null) {
                    queue.offer(top.right);
                }
            }
            res.add(list);
        }
        Collections.reverse(res);
        return res;
    }
    /**
     * 判断一棵树是不是完全二叉树
     */
    public static boolean isCompleteTree(TreeNode root){
        if (root == null) return true;
        if (root.left == null && root.right == null) {
            return true;
        }
        if (root.left == null || root.right == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode top = queue.poll();
            if (top == null) {
                break;
            }
            queue.offer(top.left);
            queue.offer(top.right);
        }
        while (!queue.isEmpty()) {
            TreeNode top = queue.poll();
            if (top != null) {
                return false;
            }
            top = queue.poll();
        }
        return true;
    }
    /**
     * 判断两棵树是否相同
     * @param p
     * @param q
     * @return
     */
    public static boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null && q != null) {
            return false;
        }
        if (p != null && q == null) {
            return false;
        }
        if (p.val != q.val) {
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    /**
     * 翻转一棵二叉树
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    /**
     * 判断一颗树是否是另一颗树的子树
     * @param root
     * @param subRoot
     * @return
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null || subRoot == null) return false;

        if (isSameTree(root, subRoot)) {
            return true;
        }
        if (isSubtree(root.left, subRoot)) {
            return true;
        }
        if (isSubtree(root.right, subRoot)) {
            return true;
        }
        return false;
    }

    /**
     * 判断一棵树是否是平衡二叉树
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        return Math.abs(leftH-rightH) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }

    /**
     * 判断一棵树是不是对称二叉树
     * @param root
     * @return
     */
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        return isSymmetricChild(root.left, root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree) {
        if (leftTree != null && rightTree == null || leftTree == null && rightTree != null) {
            return false;
        }
        if (leftTree == null && rightTree == null) {
            return true;
        }
        if (leftTree.val != rightTree.val) {
            return false;
        }
        return isSymmetricChild(leftTree.left, rightTree.right) && isSymmetricChild(leftTree.right, rightTree.left);
    }

    /**
     * 返回二叉树的最近公共祖先
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //到底了，返回null
        if (root == null) return root;
        //其中有一个节点就是当前节点 直接返回
        if (p == root || q == root) return root;
        //去左右子树找
        TreeNode leftTree = lowestCommonAncestor(root.left, p, q);
        TreeNode rightTree = lowestCommonAncestor(root.right, p, q);
        //左右子树都不为空，则当前节点就是最近公共祖先
        if (leftTree != null && rightTree != null) return root;
        //只有一边有，就把那一边结果传上来
        return leftTree != null ? leftTree : rightTree;
    }

    /**
     * 根据前序遍历数组和中序遍历数组，构建一棵二叉树
     * @param preorder
     * @param inorder
     * @return
     */
    /*public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTree(preorder, inorder, 0, inorder.length);
    }
    int index = 0;
    public TreeNode buildTree(int[] preorder, int[] inorder, int left, int right) {
        if (left >= right) return null;
        //递归就是每一层都做一样的事情
        //根据前序遍历的数组，先创建根节点
        TreeNode root = new TreeNode(preorder[index]);
        //在中序遍历的数组中，找到根节点所在的位置
        int rootIndex = left;
        while (rootIndex < right) {
            if (preorder[index] == inorder[rootIndex]) {
                break;
            }
            rootIndex++;
        }
        //找到中序序列中根节点的位置，那么就可以找下一个子树的根节点了
        index++;
        //去构建左右子树
        root.left = buildTree(preorder, inorder, left, rootIndex);
        root.right = buildTree(preorder, inorder, rootIndex + 1, right);
        return root;
    }*/

    /**
     * 根据中序遍历数组和后序遍历数组，构建一棵二叉树
      */
    /*int index = 0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        index = postorder.length - 1;
        return buildTree(inorder, postorder, 0, inorder.length);
    }


    //递归 每一层都是在相同的事
    public TreeNode buildTree(int[] inorder, int[] postorder, int left, int right) {
        if (left >= right) return null;
        //根据后序遍历数组，创建根节点
        TreeNode root = new TreeNode(postorder[index]);
        //在中序遍历数组中，找到根节点的位置
        int rootIndex = left;
        while (rootIndex < right) {
            if (inorder[rootIndex] == postorder[index]) {
                break;
            }
            rootIndex++;
        }
        index--;
        //构建右子树
        root.right = buildTree(inorder, postorder, rootIndex + 1, right);
        //构建左子树
        root.left = buildTree(inorder, postorder, left, rootIndex);
        return root;
    }*/

    /**
     * 根据二叉树创建字符串
     * @param root
     * @return
     */
    public String tree2str(TreeNode root) {
        if (root == null) return "";
        if (root.left == null && root.right == null) return String.valueOf(root.val);

        String left = tree2str(root.left);
        String right = tree2str(root.right);

        //当前层只负责合
        if (root.right == null) {
            return root.val +  "(" + left + ")";
        }
        // 其他情况：左空也要保留 ()
        return root.val + "(" + left + ")" + "(" + right + ")";
    }

    /**
     * 二叉树的前序非递归遍历
     * @param root
     * @return
     */
    /*public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.empty()) {
            TreeNode cur = stack.pop();
            res.add(cur.val);

            if (cur.right != null) stack.push(cur.right);
            if (cur.left != null) stack.push(cur.left);
        }
        return res;
    }*/
}
